package com.miracle9.game.service;

import com.miracle9.game.bean.Pager;
import com.miracle9.game.dao.*;
import com.miracle9.game.entity.*;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.util.MyUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("promoterService")
public class PromoterService
        extends BaseService {

    @Autowired
    private PromoterServiceDao1 promoterServiceDao1;
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private PayApplyServiceDao payApplyServiceDao;
    @Autowired
    private SystemConfigServiceDao systemConfigServiceDao;
    @Autowired
    private PayLogServiceDao payLogServiceDao;
    @Autowired
    private AdminServiceDao adminServiceDao;
    @Autowired
    private AdminService adminService;
    @Autowired
    private com.miracle9.game.dao.AdminLogServiceDao adminLogServiceDao;
    @Autowired
    private GameDataLogServiceDao gameDataLogServiceDao;
    @Autowired
    private Dao dao;
    @Autowired
    private UserWarningServiceDao userWarningServiceDao;
    @Autowired
    private PromoterLogServiceDao promoterLogServiceDao;

    public Map<String, Object> getPromoterList(int type, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap();
        String orgOrderBy = pager.getOrderBy();
        String orgOrder = pager.getOrder();
        if (StringUtils.isBlank(pager.getOrderBy())) {
            pager.setOrderBy("payMoney desc,expiryNum desc,username");
        } else {
            List<String> orderby = new ArrayList();
            orderby.add("payMoney");
            orderby.add("expiryNum");
            orderby.add("username");
            orderby.remove(pager.getOrderBy());
            StringBuilder sb = new StringBuilder(pager.getOrderBy() + " " + pager.getOrder());
            for (String o : orderby) {
                sb.append("," + o + " " + pager.getOrder());
            }
            pager.setOrderBy(sb.toString());
            pager.setOrder(null);
        }
        long sumGold = 0L;
        if (type == 0) {
            pager = this.promoterServiceDao1.q_CreateSqlsPager("from Promoter where parentId=0", pager, new Object[0]);
            sumGold = this.promoterServiceDao1.getSumGoldByparentId_0();
        } else {
            pager = this.promoterServiceDao1.q_CreateSqlsPager("from Promoter where parentId!=0", pager, new Object[0]);
            sumGold = this.promoterServiceDao1.getSumGoldByparentId();
        }
        pager.setOrderBy(orgOrderBy);
        pager.setOrder(orgOrder);
        map.put("pager", pager);
        map.put("gold", Long.valueOf(sumGold));
        map.put("number", Integer.valueOf(this.promoterServiceDao1.getQuantity()));
        return map;
    }

    public Map<String, Object> getPromoterPayCount() {
        Map<String, Object> result = new HashMap();
        int payCount = this.promoterServiceDao1.q_CreateSqlInt("select count(*) from Promoter where payMoney > 0 and parentId = 0", new Object[0]);
        int expiryCount = this.promoterServiceDao1
                .q_CreateSqlInt("select count(*) from Promoter where expiryNum > 0 and parentId = 0", new Object[0]);
        result.put("payCount", Integer.valueOf(payCount));
        result.put("expiryCount", Integer.valueOf(expiryCount));
        return result;
    }

    public Map<String, Object> searchPromoter(String username, int type, IoSession session) {
        Map<String, Object> result = new HashMap();
        String hql = null;
        if (type == 0) {
            hql = "from Promoter where username like ? and parentId =0";
        } else {
            hql = "from Promoter where username like ? and parentId !=0";
        }
        long sumGold = 0L;
        hql = hql + " order by payMoney desc,expiryNum desc,username";
        List<Promoter> promoters = this.promoterServiceDao1.q_CreateSqlList(hql, new Object[]{"%" + username + "%"});
        for (Promoter p : promoters) {
            sumGold += p.getGold();
        }
        result.put("gold", Long.valueOf(sumGold));
        result.put("number", Integer.valueOf(promoters.size()));
        result.put("results", promoters.toArray(new Promoter[0]));
        return result;
    }

    public synchronized Map<String, Object> addPromoter(String username, String registCode, String remark, IoSession session) {
        Map<String, Object> result = new HashMap();
        if ((this.promoterServiceDao1.getQuantityByUserName(username)) || (username.equals("admin"))) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "promoterUserExist"));
            return result;
        }
        boolean enabled = this.adminService.checkPromoterCode(registCode);
        if (!enabled) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "registCodeError"));
            return result;
        }
        int count = this.promoterServiceDao1.q_CreateSqlInt("select count(*) from Promoter where registCode = ?", new Object[]{registCode});
        if (count > 0) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "registCodeUsed"));
            return result;
        }
        int promoterCount = this.promoterServiceDao1.q_CreateSqlInt("select count(*) from Promoter", new Object[0]);
        if (promoterCount >= 100) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "promoterLimit"));
            return result;
        }
        Promoter promoter = new Promoter();
        promoter.setUsername(username);
        promoter.setLevel(1);
        promoter.setParentId(0);
        promoter.setParentName("admin");
        promoter.setPassword(MyUtil.strPwdMd5Hex("888888"));
        promoter.setRemark(remark);
        promoter.setRegistCode(registCode);
        promoter.setGoldAuth(0);
        promoter.setCreateTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        int payScale = config.getPromoterPayScale() + 5;
        if (payScale > config.getPayScale()) {
            promoter.setChildrenPayScale(config.getPayScale());
        } else {
            promoter.setChildrenPayScale(payScale);
        }
        promoter.setChildrenUserOver(-1);
        this.promoterServiceDao1.addPromoter(promoter);
        String content = "新增了直属推广员" + promoter.getUsername();
        String contentEn = "Add a direct extension which ID is " + promoter.getUsername();
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> disablePromoter(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updateState_1ById(id);
        IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id));
        if (s != null) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "disableNotice", new Object[0]));
        }
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        String content = null;
        String contentEn = null;
        if (promoter.getParentId() == 0) {
            content = "对直属推广员" + promoter.getUsername() + "进行了禁用操作";
            contentEn = "Frozen the direct extension which ID is " + promoter.getUsername();
        } else {
            content = "对非直属推广员" + promoter.getUsername() + "进行了禁用操作";
            contentEn = "Frozen the indirect extension which ID is " + promoter.getUsername();
        }
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> enablePromoter(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updateState_0ById(id);
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        String content = null;
        String contentEn = null;
        if (promoter.getParentId() == 0) {
            content = "对直属推广员" + promoter.getUsername() + "进行了解禁操作";
            contentEn = "Thaw the direct extension which ID is " + promoter.getUsername();
        } else {
            content = "对非直属推广员" + promoter.getUsername() + "进行了解禁操作";
            contentEn = "Thaw the indirect extension which ID is " + promoter.getUsername();
        }
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public synchronized Map<String, Object> deletePromoter(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        if (promoter == null) {
            result.put("success", Boolean.valueOf(true));
            return result;
        }
        this.userServiceDao.q_CreateSql("update User set promoterId=?,promoterName=? where promoterId=?", new Object[]{Integer.valueOf(promoter.getParentId()), promoter.getParentName(), Integer.valueOf(promoter.getId())}).executeUpdate();
        this.promoterServiceDao1.updatePromoterInfo(promoter);
        this.promoterServiceDao1.delete(promoter);
        int promoterCount = this.promoterServiceDao1.q_CreateSqlInt("select count(*) from Promoter where parentId=?", new Object[]{
                Integer.valueOf(promoter.getParentId())});
        int userCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where promoterId=?", new Object[]{Integer.valueOf(promoter.getParentId())});
        this.promoterServiceDao1.q_Update("update Promoter set childrenPromoterNum=?,childrenUserNum=? where id=?", new Object[]{
                Integer.valueOf(promoterCount), Integer.valueOf(userCount), Integer.valueOf(promoter.getParentId())});
        IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id));
        if (s != null) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "deleteNotice", new Object[0]));
        }
        String content = null;
        String contentEn = null;
        if (promoter.getParentId() == 0) {
            content = "对直属推广员" + promoter.getUsername() + "进行了删除操作";
            contentEn = "Delete the direct extension which ID is " + promoter.getUsername();
        } else {
            content = "对非直属推广员" + promoter.getUsername() + "进行了删除操作";
            contentEn = "Delete the indirect extension which ID is " + promoter.getUsername();
        }
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Promoter[] parentPromoterList(int id, IoSession session) {
        List<Promoter> promoters = new ArrayList();
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        if (promoter != null) {
            Promoter admin = new Promoter();
            admin.setId(0);
            admin.setUsername(MyUtil.getProperties(Integer.valueOf(resultInt(session)), "zongGongSi") + "：admin");
            if (resultInt(session) == 1) {
                admin.setUsername("admin");
            }
            promoters.add(admin);
            promoterAdd(promoter, promoters);
            List<Promoter> sameLevel = this.promoterServiceDao1.q_CreateSqlList("from Promoter where parentId = ? and id!=?", new Object[]{
                    Integer.valueOf(promoter.getParentId()), Integer.valueOf(id)});
            promoters.addAll(sameLevel);
        }
        return (Promoter[]) promoters.toArray(new Promoter[0]);
    }

    private void promoterAdd(Promoter subParent, List<Promoter> promoters) {
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(subParent.getParentId()));
        if (promoter != null) {
            promoters.add(promoter);
            promoterAdd(promoter, promoters);
        }
    }

    public synchronized Map<String, Object> updateChildrenParent(int id, int parentId, IoSession session) {
        Map<String, Object> result = new HashMap();
        Promoter parentPromoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(parentId));
        if (parentPromoter == null) {
            parentPromoter = new Promoter();
            parentPromoter.setId(0);
            parentPromoter.setUsername("admin");
        }
        int userCount = this.userServiceDao.q_CreateSql("update User set promoterId = ?,promoterName=? where promoterId=?", new Object[]{
                Integer.valueOf(parentId), parentPromoter.getUsername(), Integer.valueOf(id)}).executeUpdate();
        parentPromoter.setChildrenUserNum(parentPromoter.getChildrenUserNum() + userCount);
        this.promoterServiceDao1.q_CreateSql("update Promoter set childrenPromoterNum=0,childrenUserNum=0 where id=?", new Object[]{Integer.valueOf(id)})
                .executeUpdate();
        this.promoterServiceDao1.updatePromoterInfoAndGetPromoters(id, parentPromoter);
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        String content = null;
        String contentEn = null;
        if (promoter.getParentId() == 0) {
            if (parentPromoter.getParentId() == 0) {
                content = "将直属推广员" + promoter.getUsername() + "的下级调整至直属推广员" + parentPromoter.getUsername() + "下";
                contentEn = "Adiust the subordinates of direct extension " + promoter.getUsername() +
                        " to another direct extension " + parentPromoter.getUsername();
            } else {
                content = "将直属推广员" + promoter.getUsername() + "的下级调整至非直属推广员" + parentPromoter.getUsername() + "下";
                contentEn = "Adiust the subordinates of direct extension " + promoter.getUsername() +
                        " to another indirect extension " + parentPromoter.getUsername();
            }
        } else if (parentPromoter.getParentId() == 0) {
            content = "将非直属推广员" + promoter.getUsername() + "的下级调整至直属推广员" + parentPromoter.getUsername() + "下";
            contentEn = "Adiust the subordinates of indirect extension " + promoter.getUsername() +
                    " to another direct extension " + parentPromoter.getUsername();
        } else {
            content = "将非直属推广员" + promoter.getUsername() + "的下级调整至非直属推广员" + parentPromoter.getUsername() + "下";
            contentEn = "Adiust the subordinates of indirect extension " + promoter.getUsername() +
                    " to another indirect extension " + parentPromoter.getUsername();
        }
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> resetPromoterPwd(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updatePasswordById(id, MyUtil.strPwdMd5Hex("888888"));
        IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id));
        if (s != null) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "pwdResetNotice", new Object[0]));
        }
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        String content = null;
        String contentEn = null;
        if (promoter.getParentId() == 0) {
            content = "对直属推广员" + promoter.getUsername() + "进行了密码重置操作";
            contentEn = "Reset the password of direct extension " + promoter.getUsername();
        } else {
            content = "对非直属推广员" + promoter.getUsername() + "进行了密码重置操作";
            contentEn = "Reset the password of indirect extension " + promoter.getUsername();
        }
        addAdminLog(session, 2, content, contentEn);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> updatePromoterRemark(int id, String remark, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updateRemarkById(id, remark);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> updatePromoterKefu(int id, String kefu, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updateKefuById(id, kefu);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> updatePromoterAuth(int id, int goldAuth, int fishAuth, IoSession session) {
        Map<String, Object> result = new HashMap();
        this.promoterServiceDao1.updatePromoterAuth(id, goldAuth, fishAuth);
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    public Map<String, Object> promoterPayLogs(int id, String startDate, String endDate, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap();
        double lastTotalMoney = 0.0D;
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        pager = this.promoterServiceDao1.q_CreateSqlsPager("from PayLog where userType=1 and type =0 and userId = ? and datetime>=? and datetime<=? order by datetime desc ", pager, new Object[]{Integer.valueOf(id), startDate, endDate});
        Object[] objs = pager.getList();
        List<Object> obj = new ArrayList();
        PayLog payLog;
        for (Object o : objs) {
            payLog = (PayLog) o;
            Map<String, Object> data = new HashMap();
            data.put("datetime", payLog.getDatetime());
            data.put("username", payLog.getUsername());
            data.put("money", Double.valueOf(payLog.getMoney()));
            data.put("admin", payLog.getAdmin());
            data.put("gameGold", Integer.valueOf(payLog.getGameGold()));
            if (payLog.getExpiryType() == 0) {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "zhuDongFaQi"));
            } else {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "tgyFaQi"));
            }
            data.put("remark", payLog.getRemark());
            obj.add(data);
        }
        pager.setList(obj.toArray());
        map.put("pager", pager);
        Pager p = new Pager();
        p = (Pager) map.get("pager");
        String hql = "";
        hql = "select ifnull(sum(money),0) from pay_log where user_type=1 and type =0 and user_id=" + id + " and datetime>=? and datetime<=? ";
        Object log = this.promoterServiceDao1.getListByInterval(hql, startDate, endDate);
        for (Object o1 : (List) log) {
            lastTotalMoney = ((Number) o1).longValue();
        }
        map.put("lastTotalMoney", Double.valueOf(lastTotalMoney));
        return map;
    }

    public Map<String, Object> promoterExpiryLogs(int id, String startDate, String endDate, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap();
        double lastTotalMoney = 0.0D;
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        pager = this.promoterServiceDao1.q_CreateSqlsPager("from PayLog where userType=1 and type =1 and userId = ? and datetime>=? and datetime<=? order by datetime desc ", pager, new Object[]{Integer.valueOf(id), startDate, endDate});
        Object[] objs = pager.getList();
        List<Object> obj = new ArrayList();
        PayLog payLog;
        for (Object o : objs) {
            payLog = (PayLog) o;
            Map<String, Object> data = new HashMap();
            data.put("datetime", payLog.getDatetime());
            data.put("username", payLog.getUsername());
            data.put("money", Double.valueOf(payLog.getMoney()));
            data.put("admin", payLog.getAdmin());
            data.put("gameGold", Integer.valueOf(payLog.getGameGold()));
            if (payLog.getExpiryType() == 0) {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "zhuDongFaQi"));
            } else {
                data.put("expiryType", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "tgyFaQi"));
            }
            data.put("remark", payLog.getRemark());
            obj.add(data);
        }
        pager.setList(obj.toArray());
        map.put("pager", pager);
        Pager p = new Pager();
        p = (Pager) map.get("pager");
        String hql = "";
        hql = "select ifnull(sum(money),0) from pay_log where user_type=1 and type =1 and user_id=" + id + " and datetime>=? and datetime<=? ";
        Object log = this.promoterServiceDao1.getListByInterval(hql, startDate, endDate);
        if (log != null) {
            for (Object o1 : (List) log) {
                lastTotalMoney = ((Number) o1).longValue();
            }
        }
        map.put("lastTotalMoney", Double.valueOf(lastTotalMoney));
        return map;
    }

    public Promoter getPromoterInfo(int id, IoSession session) {
        return (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
    }

    public Map<String, Object> promoterPay(int id, int money, int type, IoSession session) {
        Map<String, Object> result = new HashMap();
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        int payGold = money * 100 / config.getPromoterPayScale();
        String remark = null;
        if (type == 0) {
            this.promoterServiceDao1.addGold(id, payGold);
            result.put("plusGold", Integer.valueOf(payGold));
        } else {
            List<PayApply> payApplys;
            synchronized (PayApplyService.expiryLock) {
                PayApply payApply = this.payApplyServiceDao.getByuserIdAndUserType_1(id, 0);
                if (payApply == null) {
                    result.put("success", Boolean.valueOf(false));
                    result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "payTimeout"));
                    return result;
                }
                remark = payApply.getRemark();
                payApply.setState(PayApply.PayApplyState.HANDLED);
                payApplys = this.payApplyServiceDao.getAllPayApply();
                for (PayApply p : payApplys) {
                    if (p.getId() == payApply.getId()) {
                        payApplys.remove(p);
                        break;
                    }
                }
                this.promoterServiceDao1.addGold(id, payGold);
                result.put("plusGold", Integer.valueOf(payGold));
                this.promoterServiceDao1.updatePayMoney(id, 0);
                IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(promoter.getId()));
                payApply.setDatetime(MyUtil.c());
                if (s != null) {
                    payApply.setNotice(true);
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "syncPayResult", new Object[]{MyUtil.format(
                            MyUtil.getSessionAttribute(s, "promoterPayApprovedTip"), new Object[]{MyUtil.c(), Integer.valueOf(payGold)})}));
                }
                this.payApplyServiceDao.update(payApply);
            }
            Map<String, Object> countMap = getPromoterPayCount();
            for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "promoterPayCount", new Object[]{countMap}));
            }
        }
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        String datetime = MyUtil.dateFormatYMD_HMS_Sting(new Date());
        PayLog payLog = new PayLog(promoter.getId(), promoter.getUsername(), datetime, money, payGold,
                admin.getUsername(), 0, admin.getType(), type, remark, 1,
                promoter.getParentId(), promoter.getGold() + payGold + promoter.getExpiryNum());
        this.payLogServiceDao.save(payLog);
        String content = "为直属推广员" + promoter.getUsername() + "充值" + money + "元";
        String contentEn = "Recharge " + money + " yuan for direct extension which ID is " + promoter.getUsername();
        addAdminLog(session, 2, content, contentEn);
        if (com.miracle9.game.util.GameParameterAssist.bx.containsKey(Integer.valueOf(id))) {
            syncPayActiveResult((IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id)), MyUtil.format(MyUtil.getSessionAttribute(session, "promoterPayActive"), new Object[]{Integer.valueOf(payGold)}));
        }
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    private static void syncPayActiveResult(IoSession ioSession, String message) {
        AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(ioSession, "syncPayActiveResult", new Object[]{message}));
    }

    public Map<String, Object> promoterExpiry(int id, int gold, int type, IoSession session) {
        if (gold < 0) {
            gold = -gold;
        }
        Map<String, Object> result = new HashMap();
        result.put("type", Integer.valueOf(type));
        result.put("plusGold", Integer.valueOf(gold));
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        double expiryMoney = MyUtil.doubleDivideCalculation(gold * config.getPromoterPayScale(), 100.0D);
        String remark = null;
        if (type == 0) {
            boolean success = this.promoterServiceDao1.addGold(id, -gold);
            if (!success) {
                result.put("success", Boolean.valueOf(false));
                result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notGold"));
                return result;
            }
        } else {
            List<PayApply> payApplys;
            synchronized (PayApplyService.expiryLock) {
                PayApply payApply = this.payApplyServiceDao.getByuserIdAndUserType_1(id, 1);
                if (payApply == null) {
                    result.put("success", Boolean.valueOf(false));
                    result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "expiryTimeout"));
                    return result;
                }
                gold = payApply.getAmmount();
                expiryMoney = MyUtil.doubleDivideCalculation(gold * config.getPromoterPayScale(), 100.0D);
                remark = payApply.getRemark();
                payApply.setState(PayApply.PayApplyState.HANDLED);
                payApplys = this.payApplyServiceDao.getAllPayApply();
                for (PayApply p : payApplys) {
                    if (p.getId() == payApply.getId()) {
                        payApplys.remove(p);
                        break;
                    }
                }
                this.promoterServiceDao1.updateExpiryNum(id, 0);
                IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(promoter.getId()));
                payApply.setDatetime(MyUtil.c());
                if (s != null) {
                    payApply.setNotice(true);
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "syncExpiryResult", new Object[]{MyUtil.format(
                            MyUtil.getSessionAttribute(s, "promoterExpiryApprovedTip"), new Object[]{MyUtil.c(), Integer.valueOf(gold)})}));
                }
                this.payApplyServiceDao.update(payApply);
            }
            Map<String, Object> countMap = getPromoterPayCount();
            for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "promoterPayCount", new Object[]{countMap}));
            }
        }
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        String datetime = MyUtil.dateFormatYMD_HMS_Sting(new Date());
        PayLog payLog = new PayLog(promoter.getId(), promoter.getUsername(), datetime, expiryMoney, gold,
                admin.getUsername(), 1, admin.getType(), type, remark, 1, promoter.getParentId(), promoter.getGold() - gold + promoter.getExpiryNum());
        this.payLogServiceDao.save(payLog);
        String content = "为直属推广员" + promoter.getUsername() + "兑换" + expiryMoney + "元";
        String contentEn = "Exchange " + expiryMoney + " coins for direct extension which ID is " + promoter.getUsername();
        addAdminLog(session, 2, content, contentEn);
        if (com.miracle9.game.util.GameParameterAssist.bx.containsKey(Integer.valueOf(id))) {
            syncExpiryActiveResult((IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id)), MyUtil.format(MyUtil.getSessionAttribute(session, "promoterExpiryActive"), new Object[]{Integer.valueOf(gold)}));
        }
        result.put("success", Boolean.valueOf(true));
        return result;
    }

    private static void syncExpiryActiveResult(IoSession ioSession, String message) {
        AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(ioSession, "syncExpiryActiveResult", new Object[]{message}));
    }

    public Map<String, Object> getPromoterPay(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        PayApply payApply = (PayApply) this.payApplyServiceDao.q_CreateSqlFilter(
                "from PayApply where userId =? and userType=1 and type=0 and state = ?", new Object[]{Integer.valueOf(id), PayApply.PayApplyState.PENDING});
        if (payApply == null) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "payTimeout"));
            return result;
        }
        result.put("success", Boolean.valueOf(true));
        result.put("remark", payApply.getRemark());
        result.put("money", Integer.valueOf(payApply.getAmmount()));
        return result;
    }

    public Map<String, Object> cancelPromoterPay(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        synchronized (PayApplyService.expiryLock) {
            PayApply payApply = this.payApplyServiceDao.getByuserIdAndUserType_1(id, 0);
            if (payApply == null) {
                result.put("success", Boolean.valueOf(true));
                return result;
            }
            payApply.setState(PayApply.PayApplyState.WAIVE);
            this.promoterServiceDao1.updatePayMoney(id, 0);
            Map<String, Object> countMap = getPromoterPayCount();
            for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "promoterPayCount", new Object[]{countMap}));
            }
            IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id));
            if (s != null) {
                payApply.setNotice(true);
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "syncPayResult", new Object[]{MyUtil.getSessionAttribute(s,
                        "promoterPayDeniedTip")}));
            }
            this.payApplyServiceDao.update(payApply);
            Object payApplys = this.payApplyServiceDao.getAllPayApply();
      /*for (PayApply p : (List)payApplys) {
        if (payApply.getId() == p.getId())
        {
          ((List)payApplys).remove(p);
          break;
        }
      }*/
            for (int i = 0; i < ((List) payApplys).size(); i++) {
                if (payApply.getId() == ((PayApply) ((List) payApplys).get(i)).getId()) {
                    ((List) payApplys).remove(((PayApply) ((List) payApplys).get(i)));
                    break;
                }
            }
            result.put("success", Boolean.valueOf(true));
            return result;
        }
    }

    public Map<String, Object> getPromoterExpiry(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        PayApply payApply = (PayApply) this.payApplyServiceDao.q_CreateSqlFilter(
                "from PayApply where userId =? and userType=1 and type=1 and state = ?", new Object[]{Integer.valueOf(id), PayApply.PayApplyState.PENDING});
        if (payApply == null) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "expiryTimeout"));
            return result;
        }
        result.put("success", Boolean.valueOf(true));
        result.put("remark", payApply.getRemark());
        result.put("gold", Integer.valueOf(payApply.getAmmount()));
        return result;
    }

    public Map<String, Object> cancelPromoterExpiry(int id, IoSession session) {
        Map<String, Object> result = new HashMap();
        synchronized (PayApplyService.expiryLock) {
            PayApply payApply = this.payApplyServiceDao.getByuserIdAndUserType_1(id, 1);
            if (payApply == null) {
                result.put("success", Boolean.valueOf(true));
                return result;
            }
            this.promoterServiceDao1.addGold(id, payApply.getAmmount());
            payApply.setState(PayApply.PayApplyState.WAIVE);
            this.promoterServiceDao1.updateExpiryNum(id, 0);
            result.put("success", Boolean.valueOf(true));
            Map<String, Object> countMap = getPromoterPayCount();
            for (IoSession as : com.miracle9.game.util.GameParameterAssist.be.values()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(as, "promoterPayCount", new Object[]{countMap}));
            }
            IoSession s = (IoSession) com.miracle9.game.util.GameParameterAssist.bx.get(Integer.valueOf(id));
            if (s != null) {
                payApply.setNotice(true);
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new com.miracle9.game.server.message.StorageMethodEntity(s, "syncExpiryResult", new Object[]{MyUtil.getSessionAttribute(s,
                        "promoterExpiryDeniedTip")}));
            }
            this.payApplyServiceDao.update(payApply);
            Object payApplys = this.payApplyServiceDao.getAllPayApply();
      /*for (PayApply p : (List)payApplys) {
        if (payApply.getId() == p.getId())
        {
          ((List)payApplys).remove(p);
          break;
        }
      }*/
            for (int i = 0; i < ((List) payApplys).size(); i++) {
                if (payApply.getId() == ((PayApply) ((List) payApplys).get(i)).getId()) {
                    ((List) payApplys).remove(((PayApply) ((List) payApplys).get(i)));
                    break;
                }
            }
            Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
            result.put("newGold", Integer.valueOf(promoter.getGold()));
            return result;
        }
    }

    public int checkPromoterSumExpiry(int id, int gold, IoSession session) {
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (config.getPromoterSumMoney() < 0) {
            return 0;
        }
        double sumMoney = this.payLogServiceDao.getSumMoneyByUserId_1(id);
        double money = MyUtil.doubleDivideCalculation(gold * config.getPromoterPayScale(), 100.0D);
        int count = 0;
        int checkMoney = config.getTempPromoterSumMoney() > 0 ? config.getTempPromoterSumMoney() : config
                .getPromoterSumMoney();
        while (sumMoney + money > checkMoney) {
            checkMoney += config.getPromoterSumMoney();
            count++;
        }
        return count;
    }

    public Map<String, Object> enterPromoterPwd(int id, String pwd, IoSession session) {
        Map<String, Object> result = new HashMap();
        int count = this.promoterServiceDao1.q_CreateSqlInt("select count(*) from Promoter where id=? and password=?", new Object[]{Integer.valueOf(id), MyUtil.strPwdMd5Hex(pwd)});
        if (count > 0) {
            result.put("success", Boolean.valueOf(true));
        } else {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "passwordError"));
        }
        return result;
    }

    public void updatePayMoney(int id, int payMoney) {
        this.promoterServiceDao1.updatePayMoney(id, payMoney);
    }

    public void updateExpiryNum(int id, int expiryNum) {
        this.promoterServiceDao1.updateExpiryNum(id, expiryNum);
    }

    public boolean addGold(int id, int gold) {
        return this.promoterServiceDao1.addGold(id, gold);
    }

    public Promoter getPromoter(int id) {
        return (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(id));
    }

    private void addAdminLog(IoSession session, int type, String content, String contentEn) {
        int adminId = ((Integer) session.getAttribute("id")).intValue();
        Admin admin = (Admin) this.adminServiceDao.getById(Integer.valueOf(adminId));
        AdminLog log = new AdminLog(admin.getUsername(), content, type, admin.getType(), contentEn);
        this.adminLogServiceDao.addAdminLog(log);
    }

    public Map<String, Object> promoterPlayLogs(int promoterId, String startDate, String endDate, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap();
        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(promoterId));
        String promoterName = promoter.getUsername();
        int firstResult = (pager.getPageNumber() - 1) * pager.getPageSize();
        int maxResults = pager.getPageSize();
        String order = "";
        String orderBy = "";
        if (pager.getOrder() == "") {
            order = "desc";
        } else {
            order = pager.getOrder();
        }
        if (pager.getOrderBy() == "") {
            orderBy = "datetime";
        } else if (pager.getOrderBy().endsWith("allGain")) {
            orderBy = "sum_ya_gold";
        } else if (pager.getOrderBy().endsWith("allPlay")) {
            orderBy = "sum_ya_gold";
        } else if (pager.getOrderBy().endsWith("allGet")) {
            orderBy = "sum_de_gold";
        } else if (pager.getOrderBy().endsWith("promoterName")) {
            orderBy = "promoter_id";
        } else {
            orderBy = pager.getOrderBy();
        }
        String hql = "select datetime,sum(sum_ya_gold),sum(sum_de_gold) from game_data_log where datetime>=? and datetime<=? and promoter_id=" + promoterId + " group by datetime order by " + orderBy + " " + order + " limit ?,?";
        List<Object[]> logs = this.gameDataLogServiceDao.getListByDateIntervalResult(hql, startDate, endDate, firstResult, maxResults);
        List<Object> datas = new ArrayList();
        for (Object[] o : logs) {
            Map<String, Object> data = new HashMap();
            data.put("datetime", o[0]);
            data.put("promoterName", promoterName);
            long sumYa = ((Number) o[1]).longValue();
            long sumDe = ((Number) o[2]).longValue();
            data.put("allPlay", Long.valueOf(sumYa));
            data.put("allGet", Long.valueOf(sumDe));
            data.put("allGain", Long.valueOf(sumYa - sumDe));
            datas.add(data);
        }
        String hql1 = "";
        hql1 = "select count(DISTINCT datetime) from game_data_log where promoter_id=" + promoterId + " and  datetime>=? and datetime<=?";
        int totalCount = 0;
        Object sum = this.gameDataLogServiceDao.s_CreateSql(hql1, new Object[]{startDate + "%", endDate + "%"}).uniqueResult();
        if (sum == null) {
            totalCount = 0;
        } else {
            totalCount = ((Number) sum).intValue();
        }
        int pageCount = (int) Math.ceil(totalCount / pager.getPageSize());
        pager.setList(datas.toArray());
        pager.setTotalCount(totalCount);
        pager.setPageCount(pageCount);
        map.put("pager", pager);
        long lastYaGold = 0L;
        long lastDeGold = 0L;
        long lastTotalGain = 0L;
        hql = "select ifnull(sum(sum_ya_gold),0),ifnull(sum(sum_de_gold),0) from game_data_log where datetime>=? and datetime<=? and promoter_id=" + promoterId;
        List<Object[]> log = this.gameDataLogServiceDao.getListByDateInterval(hql, startDate, endDate);
        for (Object[] o1 : log) {
            lastYaGold = ((Number) o1[0]).longValue();
            lastDeGold = ((Number) o1[1]).longValue();
            lastTotalGain = lastYaGold - lastDeGold;
        }
        map.put("lastTotalPlay", Long.valueOf(lastYaGold));
        map.put("lastTotalGet", Long.valueOf(lastDeGold));
        map.put("lastTotalGain", Long.valueOf(lastTotalGain));
        return map;
    }

}
